package com.dq.rbac.commons.security;

import cn.hutool.json.JSONUtil;
import com.dq.rbac.vo.R;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @project: rbac
 * @ClassName: 登录失败自定义处理器
 * @author: dq
 * @creat: 2022/12/26 14:26
 */
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        //根据用户名生成token
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        //定义返回内容
        String message = e.getMessage();
        if (e instanceof BadCredentialsException) {
            message = "用户名或密码错误!";
        }
        byte[] result = JSONUtil.toJsonStr(R.error().message(message)).getBytes(StandardCharsets.UTF_8);
        outputStream.write(result);
        outputStream.flush();
        outputStream.close();
    }
}
